#!/usr/bin/env python

import socket
import sys
import argparse
import re


def get_host_from_req(req):
    host = re.search('Host: ([\w.]*)', req).group(1)
    return host


def read_request(input):
    data = []
    while True:
        line = input.readline().strip()
        #print '[%s]' % line
        if not line and data:
            break
        if line:
            data.append(line)

    data = "\r\n".join(data)

    if not data.endswith('\r\n\r\n'):
        data += '\r\n'
    if not data.endswith('\r\n\r\n'):
        data += '\r\n'

    #print '[%s]' %  data
    return data


def replay(host, port, req):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print "===== connect to %s:%s =======" %(host,port)
    s.connect((host, port))
    s.sendall(req)
    resp = ''
    while True:
        data = s.recv(1024)
        if not data:
            break
        print data
        resp += data
    s.close()
    return resp


parser = argparse.ArgumentParser()
parser.add_argument('-p', '--port', type=int, default=80, help='server port')
parser.add_argument('-H', '--host', help='server host')
parser.add_argument('infile', nargs='?', type=argparse.FileType('r'), default=sys.stdin, help='request file')

args = parser.parse_args(sys.argv[1:])
req = read_request(args.infile)
if not args.host:
    args.host = get_host_from_req(req)

replay(args.host, args.port, req)
